import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {
  const { pathname, searchParams } = req.nextUrl;

  // 检查是否是 dashboard 路径（兼容有无 basePath）
  const isDashboard = pathname === '/dashboard' || pathname === '/aoshu/dashboard' || pathname.endsWith('/dashboard');

  // 对于 Dashboard 路径，如果没有缓存破坏参数，强制重定向添加时间戳
  if (isDashboard && !searchParams.has('v')) {
    const url = req.nextUrl.clone();
    url.searchParams.set('v', Date.now().toString());
    console.log('[Middleware] Redirecting:', pathname, '→', url.pathname + url.search);
    return NextResponse.redirect(url, { status: 307 });
  }

  // 定义需要认证的路径
  const protectedPaths = [
    '/dashboard',
    '/learn',
    '/practice',
    '/mistakes',
    '/profile',
    '/admin'
  ];

  // 检查是否是受保护的路径
  const isProtectedPath = protectedPaths.some(path =>
    pathname.startsWith(path)
  );

  // 对于受保护的路径，暂时不做拦截，让页面自己处理认证
  // 这样可以避免middleware和客户端localStorage之间的同步问题

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * 匹配所有请求路径，除了：
     * - _next/static (静态文件)
     * - _next/image (图片优化文件)
     * - favicon.ico (网站图标)
     * - public文件夹中的文件
     */
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
};
